package com.edu.dgut.controller;

import com.edu.dgut.dao.dailysalesRepository;
import com.edu.dgut.entity.dailysalesEntity;
import com.edu.dgut.service.mapObjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
@RequestMapping("/")
@PreAuthorize("hasAnyRole('ROLE_ADMIN','ROLE_USER')")
public class dailysalesController {

    @Autowired
    private dailysalesRepository dailysales;

    private mapObjectService mapObject = new mapObjectService();

    //查询所有日销售额
    @RequestMapping("getAlldailysales")
    @ResponseBody
    public Map<String, Object> findAll(){
        List<dailysalesEntity> list = new ArrayList<>();
        list = dailysales.findAll();
        return mapObject.put(list);
    }

    //通过日期查找日销售额
    @RequestMapping("getByDailyDate")
    @ResponseBody
    public Map<String, Object> getByDailyDate(String  date) {
        List<dailysalesEntity> result = dailysales.findByDate(date);
        return mapObject.put(result);
    }

    //添加或修改日销售额信息
    @RequestMapping("modifyDailysales")
    @ResponseBody
    public Map<String, Object> saveOrModifyDailysales(@RequestBody dailysalesEntity new_dailysales) {
        List<dailysalesEntity> old_dailysales = dailysales.findByDate(new_dailysales.getDate());
        if(old_dailysales.size() != 0){
            new_dailysales.setDailysales_id(old_dailysales.get(0).getDailysales_id());
        }
        new_dailysales = dailysales.save(new_dailysales);
        Map<String,Object> map = new HashMap<String,Object>();
        if(new_dailysales != null) {
            map.put("status", 1);
        }else {
            map.put("status", 0);
        }
        return map;
    }

    //删除日销售额
    @RequestMapping("deleteByDailyDate")
    @ResponseBody
    public Map<String, Object> deleteByDailyDate(String date) {
        int i = dailysales.deleteByDate(date);
        Map<String,Object> map = new HashMap<String,Object>();
        if(i >= 1) {
            map.put("status", 1);
        }else {
            map.put("status", 0);
        }
        return map;
    }
}
